<template>
  <label class="checkbox" :disabled="_disabled">
    <i class="fa" :class="_checked?'fa-check-square':'fa-square-o'"></i>
    <input v-if="trueLabel || falseLabel" type="checkbox" :checked="_checked" :true-value="trueLabel" :false-value="falseLabel" v-model="model" :name="name" :disabled="_disabled"  @change="handleChange">
    <input v-else type="checkbox" :checked="_checked" :value="label" v-model="model" :name="name" :disabled="_disabled" @change="handleChange">
      <slot></slot>
      <template v-if="!$slots.default">{{label}}</template>
  </label>
</template>
<script>
  export default {
    name: "xCheckbox",
    inject: {
      xCheckboxGroup: {
        default: ""
      }
    },
    props: {
      disabled: Boolean,
      name: String,
      value: null,
      label: [String, Number, Boolean],
      trueLabel: [String, Number],
      falseLabel: [String, Number],
    },
    computed: {
      isGroup() {
        return this.xCheckboxGroup !== ""; //是否包含与radio-group中
      },
      model: {
        get() {
          //获取时触发
          return this.isGroup ? this.xCheckboxGroup.value : this.value;
        },
        set(val) {
          //赋值时触发
          this.isGroup
            ? this.xCheckboxGroup.$emit("input", val) //通过input完成双向绑定
            : this.$emit("input", val);
        }
      },
      _disabled() {
        return this.isGroup ? this.xCheckboxGroup.disabled : this.disable;
      },
      _checked() {
        if ({}.toString.call(this.model) === "[object Boolean]") {
          return this.model;
        } else if (Array.isArray(this.model)) {
          return this.model.includes(this.label)
        } else if (this.model !== null && this.model !== undefined) {
          return this.model === this.trueLabel
        }
      }
    },
    methods: {
      handleChange() {
        this.$nextTick(() => {
          this.$emit("change", this.model);
          this.isGroup && this.xCheckboxGroup.$emit("handleChange", this.model);  //如Group存在，触发其handleChange事件
        });
      }
    }
  };

</script>